#include "../include/Acceptor.h"
#include "Acceptor.h"

void Acceptor::HandleRead()
{
    while (true)
    {
        int newfd = _socket.Accept();
        if (newfd == DefaultFD)
        {
            if (errno == EAGAIN || errno == EWOULDBLOCK)
            {
                break;
            }
            else
            {
                break;
            }
        }
        // 这里是监听新连接，应该使用新连接的fd
        if (_accept_cb)
            _accept_cb(newfd);
    }
}

int Acceptor::CreateServer(uint16_t port)
{
    bool ret = _socket.CreateServerConn(port);
    assert(ret == true);
    return _socket.getFd();
}
Acceptor::Acceptor(EventLoop *loop, uint16_t port)
    : _socket(CreateServer(port)),
      _loop(loop),
      _channel(_loop, _socket.getFd()) { _channel.SetReadCallBack(std::bind(&Acceptor::HandleRead, this)); }

void Acceptor::SetAcceptorCallBack(const AcceptorCallBack &cb) { _accept_cb = cb; }

// 从构造函数中分离出来，防止套接字刚创建就有了事件，但是回调函数还未设置，这时就没办法处理
void Acceptor::Listen() { _channel.EnableRead(); }
